<template>
  <d2-container>
    <el-main>
      <el-form ref="productForm" :model="productForm" label-width="80px" label-position="left"
               :rules="formRules">

        <el-form-item label="商品名称" prop="name" v-if="productIn == undefined">
          <el-input placeholder="请输入商品名称" v-model="productForm.name" ></el-input>
        </el-form-item>

        <el-form-item style='width: 300px' label="商品名称" prop="name" v-if="productIn != undefined">

            <el-select
                            v-model="selectedProduct"
                      @change="changeProduct">
                        <el-option
                                v-for="item in productList"
                                :label="item.name"
                                :value="item._id"
                                filterable
                        ></el-option>
                    </el-select>
        </el-form-item>





        <el-form-item label="种类" prop="productCategory">
          <el-select v-model="productForm.productCategory" multiple filterable placeholder="请选择种类" :disabled="disabled || (productIn != undefined)">
            <el-option
                    v-for="item in productCategoryList"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="进货价" prop="costPrice">
          <el-input
                  placeholder="成本价格"
                  type='number'
                  v-model.number="productForm.costPrice"
                  min="0"
                  :disabled="disabled || (productIn != undefined)"
          ></el-input>
        </el-form-item>

        <el-form-item label="批发价" prop="wholeSalePrice" v-if="headquarter">
          <el-input
                  placeholder="批发价格"
                  type='number'
                  v-model.number="productForm.wholeSalePrice"
                  min="0"
                  
                  :disabled="disabled || (productIn != undefined)"
          ></el-input>
        </el-form-item>

        <el-form-item label="零售价" prop="sellingPrice">
          <el-input
                  placeholder="零售价格"
                  v-model.number="productForm.sellingPrice"
                  type="number"
                  min="0"
                  :disabled="disabled || (productIn != undefined)"
          ></el-input>
        </el-form-item>

        <el-form-item label="库存" prop="storage">
          <el-input :placeholder="storageText" v-model.number="productForm.storage" type="number" min="0" step='1' :disabled="(productIn == undefined) && (!new1)"></el-input>
        </el-form-item>

        <el-form-item label="现有库存" v-if="productIn != undefined">
          <el-input placeholder="现有库存" v-model.number="productForm.existStorage" type="number" min="0"  step='1' :disabled='true'></el-input>
        </el-form-item>
         <el-form-item label="备注" v-if="productIn != undefined">
          <el-input placeholder="库存调整" v-model.number="productForm.memoIn" ></el-input>
        </el-form-item>
         

      </el-form>
    </el-main>
    <el-footer style="text-align: center">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="resetForm('productForm')">重置</el-button>
      <el-button @click="edit" v-show="editShow">修改</el-button>
    </el-footer>
  </d2-container>
</template>


<script>
// import { request } from "http";
import request from "@/plugin/axios";
import { constants } from 'crypto';
import {mapState} from "vuex";

export default {
  data() {
    return {
      formRules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        studentId: [
          {required: true, message: '请输入学号', trigger: 'change'}
        ],
        gender: [
          {required: true, message: '请选择学生性别', trigger: 'change'}
        ],
        age: [
          {required: true, message: '请输入家长年龄', trigger: 'change'},
          {type: 'number', min: 5, max: 100, message: '年龄范围在5-100之间', trigger: 'change'}

        ],
        school: [
          {required: true, message: '请选择所在校区', trigger: 'change'}
        ],
        buyer: [
          {required: true, message: '请选择购买者类型', trigger: 'change'}
        ],
        staff: [
          {required: true, message: '请选择购买者类型', trigger: 'change'}
        ],
        student: [
          {required: true, message: '请选择学生', trigger: 'change'}
        ],
        payType: [
          {required: true, message: '请选择付费类型', trigger: 'change'}
        ],
        cellphone: [
          {required: true, message: '手机号不能为空', trigger: 'change'},
          {type: 'number', message: '请输入11位合法手机号', trigger: 'change'}
        ],
        birthday: [
          {type: 'date', required: true, message: '请选择出生日期', trigger: 'blur'}
        ],
        selectedSchoolList: [
          {type: 'array', required: true, message: '请选择购买校区', trigger: 'blur'}
        ],
        selectedStudentList: [
          {type: 'array', required: true, message: '请选择购买学生', trigger: 'blur'}
        ],
        productOrder: [
          {type: 'array', required: true, message: '请选择采购商品', trigger: 'blur'}
        ],
        payWay: [
          {required: true, message: '请选择支付方式', trigger: 'change'}
        ],
        payStatus: [
          {required: true, message: '请选择支付状态', trigger: 'change'}
        ],
        hasBonus: [
          {required: true, message: '请选择是否提成', trigger: 'change'}
        ],
        type: [
          {required: true, message: '请选择充值类型', trigger: 'change'}
        ],
        discount: [
          {required: true, min: 0, type: 'number', message: '请输入合法优惠金额', trigger: 'change'}
        ],
        course: [
          {type: 'array', required: true, message: '请选择课程', trigger: 'blur'}
        ],
        total: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', message: '请输入合法价格', trigger: 'change'}
        ],
        hour: [
          {required: true, message: '时长不能为空', trigger: 'change'},
          {type: 'number', message: '请输入时长', trigger: 'change'}
        ],
        storage: [
          {required: true, message: '不能为空', trigger: 'change'},
          {type: 'number', message: '请输入整数', trigger: 'change'}
        ],
        sellingPrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', min:0,message: '请输入正数', trigger: 'change'}
        ],
        wholeSalePrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', min:0, message: '请输入正数', trigger: 'change'}
        ],
        costPrice: [
          {required: true, message: '价格不能为空', trigger: 'change'},
          {type: 'number', min:0,message: '请输入正数', trigger: 'change'}
        ],

      },
      productForm :{
        name: undefined,
        costPrice: undefined,
        wholeSalePrice: undefined,
        sellingPrice: undefined,
        storage: undefined,
        school: undefined,
        productCategory: undefined,
        _id : undefined,
        memoIn : '库存调整'

      },
      storageText : '',
      editShow: false,
      disabled: false,
      id: undefined,
      schoolList:[],
      productIn : undefined,
      new1 : true,
      selectedProduct : undefined,
      // department: undefined,
      // departmentList:[],
      productList:[],
      productCategoryList:[],

    };
  },
  computed:{
    ...mapState('d2admin/user', ['info']),
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submit() {
      let data = {};
      let url = "/product/addProduct";
      if (this.headquarter){
        if (this.productForm.wholeSalePrice == undefined){
          this.$alert('','批发价格不能为空')
          return false
        }
        if (parseFloat(this.productForm.wholeSalePrice) < 0 ){
          this.$alert('','批发价格不能小于0')
          return false
        }
      }
      if (!parseInt(this.productForm.storage)){
          this.$alert('','请输入正确库存')
          return false
        }
      if (this.id != undefined) {
        data.product = this.id;
        url = "/product/updateProduct";
      }
      else if (this.productIn != undefined){
        url = "/productOrder/productIn"
        if (!this.productForm._id){
          this.$alert('','请选择商品')
          return false
        }
      }
      data.name = this.productForm.name;
      data.school = this.school;
      data._id = this.productForm._id
      // (data.department = this.department),
      data.productCategory = this.productForm.productCategory;
      data.costPrice = this.productForm.costPrice;
      data.wholeSalePrice = this.productForm.wholeSalePrice;
      data.sellingPrice = this.productForm.sellingPrice;
      data.storage = this.productForm.storage;
      data.staff = this.agent
      data.memoIn = this.productForm.memoIn
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.productForm = {
                  name: undefined,
                  costPrice: undefined,
                  wholeSalePrice: undefined,
                  sellingPrice: undefined,
                  storage: undefined,
                  school: undefined,
                  productCategory: undefined,
                  _id : undefined,
                  memoIn : '库存调整'
                }
                this.selectedProduct = undefined
          this.$router.push({path:"/product-list"})
          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
        // 返回数据
      });
    },
    edit() {
      this.disabled = false;
    },
    schoolSelected() {
      // this.getDepartmentList(1, 99999, this.school);
    },
    filterMethod(query, item) {
      return item.name.indexOf(query) != -1;
    },

    changeProduct(){
      let index = this.productList.map(function(e){return e._id}).indexOf(this.selectedProduct)
      this.productForm = this.productList[index]
      this.productForm.existStorage = this.productList[index].storage
      this.productForm.storage = undefined


    },
    getProductOne(id) {
      request({
        url: "/product/getProductOne",
        method: "post",
        data: { id: id }
      }).then(res => {
        (this.productForm._id = id),
        (this.id = res.data._id),

          (this.productForm.name = res.data.name),
          (this.productForm.school = res.data.school),
          // (this.department = res.data.department),
          (this.productForm.productCategory = res.data.productCategory),
          (this.productForm.costPrice = res.data.costPrice),
          (this.productForm.wholeSalePrice = res.data.wholeSalePrice),
          (this.productForm.sellingPrice = res.data.sellingPrice),
          (this.productForm.storage = res.data.storage);
      });
    },
    getSchoolList() {
      this.schoolList = this.info.school;
      this.productForm.school = this.schoolList[0];
    },
    getCategoryList(pageSize) {
      request({
        url: "/productCategory/getProductCategoryList",
        method: "post",
        data: { page:this.page,pageSize: pageSize,school:this.school }
      }).then(res => {
        this.productCategoryList = res.data.productCategory;
      });
    },
    getProductlist() {
      request({
        url: "/product/getProductlist",
        method: "post",
        data: { page:1,pageSize: 9999 ,school:this.school}
      }).then(res => {
        this.productList = res.data.product;
      });
    }
  },

        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.productForm = to.meta.productForm
                  v.selectedProduct = to.meta.selectedProduct
                  to.meta.productForm = undefined
                  to.meta.keep = undefined
                  to.meta.selectedProduct = undefined
                })
            }
            else{
                next()
            }
            console.log(to,from,'toto')
            next()

        },
        beforeRouteLeave(to,from,next){
          if (this.$route.query.id == undefined) {
            from.meta.keep = true
            from.meta.productForm = this.productForm      
            from.meta.selectedProduct = this.selectedProduct    
          }
          if (this.refresh){
            to.meta.refresh = 'a'
            this.refresh = undefined
          }

          next()
        },

  created() {
    if (this.$route.query.id != undefined) {
      this.editShow = true;
      this.disabled = true;
      this.new1 = false
      this.getProductOne(this.$route.query.id);
    }
        this.school = this.info.school[0]._id
                        this.agent = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
    this.productIn = this.$route.query.productIn
    if (this.productIn){
      this.storageText = '修改库存：正数为加，负数为减'
      this.getProductlist()
    }
    this.getSchoolList()
    this.getCategoryList(-1)
    if (( this.info.school[0].headquarter == 1) || ( this.info.school[0].headquarter == 2)){
              this.headquarter = true
        }
    
  }
};
</script>
